﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;

using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Graphics;
using Microsoft.Xna.Framework.Audio;

namespace DarwinIsDead.Bullets {
    class Mortar : Bullet {
        private float airTime;
        private float airCounter;

        private Texture2D shadow;
        private float shadowCounter;
        private float shadowScale;

        private Stream explosionStream;
        private SoundEffect explosion;
        private SoundEffectInstance explosionInstance;
        private AudioEmitter audioEmitter;

        public Mortar(World world, bool friendly, int damage)
            : base(world, world.Game.GraphicsDevice.Viewport.Width,
                   world.Game.GraphicsDevice.Viewport.Height, friendly, 15) {
            airTime = 3f;
            airCounter = 0f;

            shadow = World.Game.Content.Load<Texture2D>("Sprites\\sprShadow");
            shadowScale = 0.6f;
            shadowCounter = 0.0f;

            explosionStream = TitleContainer.OpenStream("Content\\Sounds\\sndNukesplosion");
            explosion = SoundEffect.FromStream(explosionStream);
            explosionInstance = explosion.CreateInstance();

            audioEmitter = new AudioEmitter();
        }

        public override void Fire() {
            // We don't want collision just yet.  The mortar is a delayed
            // bullet, so we'll enable Solidity later.
            Active = true;
            Solid = false;
        }

        public override void Collision(Entity other, Rectangle overlap) {
            if ((!Friendly && other is Player) ||
                (Friendly && other is Zombie)) {
                if (NotifyDamage != null) {
                    NotifyDamage(Damage);
                }
            }
        }

        protected override void InternalUpdate(GameTime gameTime) {
            if (Solid) {
                // We only want to be solid for one frame, so we don't cause
                // continuous damage
                Active = false;
                Solid = false;
            } else {
                float dt = gameTime.ElapsedGameTime.Milliseconds / 1000f;
                airCounter += dt;
                if (airCounter > airTime) {
                    Solid = true;

                    audioEmitter.Position = new Vector3(Position.X, Position.Y,
                        0f);
                    explosionInstance.Apply3D(World.AudioListener, audioEmitter);
                    explosionInstance.Play();
                } else {
                    shadowCounter = shadowScale * (airCounter / airTime);
                }
            }
        }

        protected override void InternalDraw(SpriteBatch spriteBatch) {
            
        }
    }
}
